package com.xuecheng.manager_course.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.course.CourseBase;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manager_course.dao.CourseBaseMapper;
import com.xuecheng.manager_course.dao.CourseBaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class CourseBaseService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseBaseRepository courseBaseRepository;
    public QueryResponseResult<CourseInfo> findCourseList(int page, int size, CourseListRequest courseListRequest){

        PageHelper.startPage(page,size);
        Page<CourseInfo> courseList = courseBaseMapper.findCourseListByRequest(courseListRequest);


        QueryResult<CourseInfo> result = new QueryResult<>();
        result.setList(courseList.getResult());
        result.setTotal(courseList.getTotal());
        return new QueryResponseResult<CourseInfo>(CommonCode.SUCCESS,result);
    }
        @Transactional
        public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
        if (id.equals(courseBase.getId())){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        Optional<CourseBase> byId = courseBaseRepository.findById(id);
        if (!byId.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CourseBase courseBaseOld = byId.get();
        courseBaseOld.setName(courseBase.getName());
        courseBaseOld.setUsers(courseBase.getUsers());
        courseBaseOld.setSt(courseBase.getSt());
        courseBaseOld.setStudymodel(courseBase.getStudymodel());
        courseBaseOld.setDescription(courseBase.getDescription());
        courseBaseRepository.save(courseBaseOld);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
